<template>
	<view class="wrap">
		<view class="top"></view>
		<view class="content">
			<view class="title u-m-b-auto">手机快捷注册</view>

			<u-input v-if="registerType == 2" class="un" v-model="mobile" placeholder="请输入手机号" border="bottom"
				maxlength="11" clearable></u-input>


			<u-input v-if="registerType == 1" class="un" v-model="mobile" placeholder="请点击右按钮获取手机号" border="bottom"
				disabled="true" disabledColor="none">
				<template slot="suffix">
					<button v-if="$u.test.isEmpty(mobile)" class="get-mobile-btn u-font-26" open-type="getPhoneNumber"
						@getphonenumber="getPhoneNumber">获取微信绑定号码</button>
				</template>
			</u-input>

			<u-input v-if="registerType == 1 || registerType == 2" class="un" v-model="name" placeholder="请输入商家名称或姓名"
				border="bottom" maxlength="20" clearable></u-input>

			<u-input v-if="registerType == 2" class="un" v-model="code" placeholder="请输入验证码" border="bottom"
				maxlength="6" type="number" clearable>
				<template slot="suffix">
					<u-code class="u-font-26" ref="uCode" @change="codeChange" seconds="60"
						changeText="X秒重新发送"></u-code>
					<u-button class="u-font-26" @tap="getCode" :text="tips" type="success" size="mini"
						:customStyle="getCodeBtnStyle"></u-button>
				</template>
			</u-input>

			<u-input v-if="registerType == 1 || registerType == 2" class="pwd" v-model="password" type="password"
				placeholder="请输入登录密码" border="bottom" maxlength="18" clearable></u-input>

		</view>
		<view class="registerTypeList" v-if="registerType == 0">
			<u-button text="微信手机号注册" @click="weiXinAppletLogin(1)" :customStyle="wxMobileRegisterBtnStyle" />
			<view class="u-m-b-50"></view>
			<u-button text="自定义手机号注册" @click="switchRegister(2)" :customStyle="diyMobileRegisterBtnStyle" />
		</view>

		<view v-if="registerType != 0">
			<u-button text="注 册" @tap="submit" :customStyle="registerBtnStyle" />
		</view>

		<view class="tool u-font-24" v-if="registerType != 0">
			<view>
				<text>已有账号，</text>
				<text class="go-login" @click="nav('/pages-other/login/login')">去登录</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				mobile: null,
				password: '',
				name: null,
				code: null,
				isPrimary: false,
				registerBtnStyle: {
					width: '636rpx',
					height: '88rpx',
					borderRadius: '120rpx',
					background: '#6072FF',
					color: '#fff',
				},

				wxMobileRegisterBtnStyle: {
					width: '636rpx',
					height: '88rpx',
					borderRadius: '120rpx',
					background: '#6072FF',
					color: '#fff',
				},

				diyMobileRegisterBtnStyle: {
					width: '636rpx',
					height: '88rpx',
					borderRadius: '120rpx',
					// background: '#6072FF',
					color: 'rgba(0, 0, 0, 0.4)',
				},

				tips: '',
				value: '',

				getCodeBtnStyle: {
					color: '#FF8000',
					background: 'none',
					borderColor: '#FF8000',
				},

				// 是否有sessionKey
				hasSessionKey: false,

				// 注册类型：0没选，1微信手机号注册，2自定义手机号注册
				registerType: 2,
				// 小程序登录获取到sessionKey，在后端临时存储在sessionKeyId
				sessionKeyId: null,
				verifyType: 1,
				agencyId: null,
			}
		},
		onLoad(options) {
			if (options.agencyId) {
				this.agencyId = options.agencyId;
			}
		},
		methods: {

			submit() {

				if (this.registerType != 1 && this.registerType != 2) {
					this.$helpers.toast('注册类型有误');
					return
				}

				if (this.registerType == 1) {
					if (this.$u.test.isEmpty(this.sessionKeyId)) {
						this.$helpers.toast('sessionKeyId有误');
						return
					}
				}

				if (this.registerType == 2) {
					if (this.$u.test.isEmpty(this.mobile)) {
						this.$helpers.toast('请输入手机号');
						return
					}
					if (!this.$u.test.mobile(this.mobile)) {
						this.$helpers.toast('手机号格式有误');
						return
					}

					if (this.$u.test.isEmpty(this.code)) {
						this.$helpers.toast('请输入验证码');
						return
					}
				}

				if (this.$u.test.isEmpty(this.name)) {
					this.$helpers.toast('请输入商家名称或姓名');
					return
				}

				this.password = this.$u.trim(this.password, 'all')
				if (this.$u.test.isEmpty(this.password)) {
					this.$helpers.toast('请输入登录密码');
					return
				}
				if (this.password.length < 6) {
					this.$helpers.toast('登录密码至少要6位');
					return
				}

				var params = {
					key: this.key,
					name: this.name,
					smsCode: this.code,
					mobile: this.mobile,
					agencyId: this.agencyId,
					password: this.password,
					sessionKeyId: this.sessionKeyId,
				}


				uni.showLoading({
					title: '注册中',
					mask: true,
				})

				var registerUrl = null;
				if (this.registerType == 2) {
					registerUrl = 'user.register';
				} else if (this.registerType == 1) {
					registerUrl = 'user.registerByAppletMobile';
				} else {
					this.$helpers.toast('注册类型有误');
					return;
				}
				console.log("registerUrl:" + registerUrl)

				this.$api(registerUrl, params).then(res => {
					uni.hideLoading();
					if (res.status == 0) {
						this.$store.commit("SET_TOKEN", res.data.token);
						this.getUserInfo();
						this.$helpers.toast("注册成功", 'success', 3000, true, () => {
							uni.reLaunch({
								url: '/pages/home/home?theStatusOfTheInput=true'
							})
						})
					} else {
						this.$helpers.toast('注册失败：' + res.msg);
					}
				}).catch(err => {
					uni.hideLoading();
				})
			},

			getUserInfo() {
				this.$api('user.getUserInfo').then(res => {
					if (res.status == 0) {
						this.$store.commit("SET_USER_INFO", res.data);
					}
				})
			},

			switchRegister(type) {
				this.registerType = type;
			},

			weiXinAppletLogin() {
				var that = this;
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						console.log('code:' + JSON.stringify(loginRes));
						uni.showModal({
							title: '提示',
							content: '请授权注册',
							cancelText: '取消',
							confirmText: '授权',
							cancelColor: '#A8A8A8',
							showCancel: true,
							success(res) {
								console.log(res);

								//如果用户点击了确定按钮
								if (res.confirm) {
									uni.getUserProfile({
										desc: '获取你的昵称、头像、地区及性别',
										success: function(res) {
											console.log(res);

											uni.showLoading({
												title: '授权中...',
												mask: true
											});

											let params = {
												code: loginRes.code,
												encryptedData: res.encryptedData,
												iv: res.iv
											};

											that.$api('applet.login', params).then(res => {
												uni.hideLoading();
												if (res.status == 0) {
													uni.showModal({
														title: '登录',
														content: '当前微信已绑定运营账号，是否登录？',
														cancelText: '取消',
														confirmText: '登录',
														showCancel: true,
														success(r) {
															if (r
																.confirm) {
																that.$store
																	.commit(
																		"SET_TOKEN",
																		res
																		.data
																		.token
																		)
																res.data
																	.token =
																	null;
																that.$store
																	.commit(
																		"SET_USER_INFO",
																		res
																		.data
																		);

																uni.reLaunch({
																	url: '/pages/home/home'
																})
															} else {
																that.$helpers
																	.toast(
																		'取消登录'
																		);
															}
														}
													});
													return
												} else if (res.status == 10001 ||
													res.status == '10001') {
													that.registerType = 1;
													// 暂时将sessionKeyId存放到这里
													that.sessionKeyId = res.msg;
													console.log("res.msg" + res
														.msg)
													console.log("sessionKeyId" +
														that.sessionKeyId)
													// that.$helpers.toast('登录成功，', 'none', 2000, true, () => {})
													return;
												} else {
													that.$helpers.toast('请求数据失败:' +
														res.msg);
													return;
												}
											}).catch(err => {
												uni.hideLoading();
											})
										},
										fail: function(res) {
											$helpers.toast('用户拒绝授权');
											console.log(res);
											//拒绝授权
											return;
										}
									});
								}
							}
						});
					}
				});
			},

			getPhoneNumber(e) {
				try {

					if (this.$u.test.isEmpty(this.sessionKeyId)) {
						this.$helpers.toast('标识丢失，请重新进去页面');
						return;
					}
					/**
					 * h9XLiaa2itKo2K************U1jT1TZVz2FrnMNqLF6MOwQsJ4kl0G8EVO9NGMhw==
					 */
					console.info(e);
					if (this.$u.test.isEmpty(e.detail.iv) || this.$u.test.isEmpty(e.detail.encryptedData)) {
						this.$helpers.toast('获取手机号失败，请稍后重试！');
						return;
					}

					uni.showLoading({
						title: '获取中...',
						mask: true
					});

					let params = {
						iv: e.detail.iv,
						sessionKeyId: this.sessionKeyId,
						encryptedData: e.detail.encryptedData
					};

					this.$api('applet.getPhoneNumber', params).then(res => {
						uni.hideLoading();
						if (res.status == 0) {
							this.mobile = res.data.mobile;
						} else {
							this.$helpers.toast('请求数据失败:' + res.msg);
						}
					}).catch(err => {
						uni.hideLoading();
					})
				} catch (err) {
					uni.hideLoading();
					console.error('getPhoneNumber捕抓到异常' + err.message);
				}
			},

			codeChange(text) {
				this.tips = text;
			},

			// 获取验证码
			getCode() {
				if (!this.$refs.uCode.canGetCode) {
					return;
				}

				if (this.$u.test.isEmpty(this.mobile)) {
					this.$helpers.toast('手机不能为空');
					return;
				}

				uni.showLoading({
					title: '发送中',
					mask: true,
				})

				var params = {
					mobile: this.mobile,
					verifyType: this.verifyType
				}
				this.$api('user.smsCode', params).then(res => {
					if (res.status == 0) {
						uni.hideLoading();
						this.$refs.uCode.start();
						this.$helpers.toast('验证码已发送');
					} else {
						uni.hideLoading();
						this.$helpers.toast('短信发送失败：' + res.msg);
					}
				})

			},

			nav(u) {
				uni.navigateTo({
					url: u
				})
			}
		}
	};
</script>

<style lang="scss" scoped>
	.wrap {
		background-color: #fff;
		height: 100vh;
		font-size: 28rpx;

		.content {
			/deep/ .uni-input-placeholder {
				color: grey !important;
			}

			width: 600rpx;
			margin: 0 auto;
			padding-top: 200rpx;

			.title {
				text-align: left;
				font-size: 46rpx;
				font-weight: 500;
				margin-bottom: 100rpx;
			}

			/deep/ .u-input {
				margin-bottom: 70rpx;
			}

			.get-mobile-btn {
				color: #6072FF;
				background: none;
				padding: 0;
			}

			button:after {
				border: 0rpx;
			}
		}

		.tool {
			width: 600rpx;
			margin: 0 auto;
			margin-top: 42rpx;
			color: rgba(0, 0, 0, 0.7);
			text-align: center;

			.go-login {
				color: #6072FF
			}
		}

		.registerTypeList {
			margin-top: 240rpx;
		}
	}
</style>
